<?php
namespace Admin\Controller;
use Admin\Controller\CommonController;
/**
 * 商品入库控制器
 */
class StorageController extends CommonController{
	// protected $search_where = array();//列表页面查询条件，用于构造sql语句
 	// protected $search_value = array();//列表页面查询条件，用于表单赋值
	public function index(){
		$pageNum=I('pageNum',1,intval);//第几页
		$numPerPage=I('numPerPage',10,intval);//每页显示条数
		//获取排序的字段及排序方式
		$orderField=$_POST['_order']?$_POST['_order']:'sequence';
		$orderDirection=$_POST['_sort']?$_POST['_sort']:'desc';
		//组合排序字符串
		$orders=($orderField.' '.$orderDirection);
		//加载检索的基础数据
		$this->search();
		//检索条件
        if($_POST['search_where']){
            $this->search_where=$_POST['search_where'];
        }

        $where=$this->_search();

        //get方式查看入库明细
        if(!empty($_GET)){
        	if(isset($_GET['sequence'])){
        		$where['sequence']=array('eq',$_GET['sequence']);
        		$search_where['sequence']['like']=$_GET['sequence'];
        		$this->assign('search_where',$search_where);
        	}
        }

    	//在where条件中增加未删除的判断条件
       	$where['del']=array('eq','0');
       	unset($where['goods_name']);
       	session('excel_where',$where);
		$db=D('StorageView');
		//获取总数据条数
		$count=$db->where($where)->count();
		$this->assign('totalCount',$count);//数据的总条数
		$this->assign('numPerPage',$numPerPage);//每页显示多少条
		$this->assign('pageNumShown',6);//页标数字多少个
		$this->assign('currentPage',$pageNum);//当前是第几页
		$page= new \Think\Page($count,$numPerPage);
		$this->list=$db->limit($numPerPage)->Page($pageNum)->order($orders)->where($where)->select();
		
		//权限菜单的显示与隐藏	
		$this->assign('storage_addId',58);//添加
		$this->assign('storage_delId',90);//删除
		$this->assign('storage_delAllId',89);//批量删除
		$this->assign('storage_editId',91);//编辑
		$this->assign('storage_confirmId',92);//审核
		$this->assign('export_excel',134);//导出报表


		$this->display();
	}


	//添加数据记录
	public function add(){
		if(!empty($_POST)){
			$arr=$_POST;
			$depot_id=I('depot_id',intval);
			if(!$depot_id) $this->error('请输入入库库房');
			$supplier_id=I('supplier_id',intval);
			if(!$supplier_id) $this->error('请输供应商名称');
			foreach ($arr['goods_number'] as $v) {
				if ($v==0) $this->error('产品数量不能为0');
			}
			foreach ($arr['goods_price'] as $v) {
				if ($v==0) $this->error('产品价格不能为0');
			}
			//入库商品的总数量
			$count=count($arr['goods_id']);		
			$t=time();
			$date=strtotime($arr['date']);
			$db=M('Code');
			//获取入库编码
			$sql="SELECT nextval('SEQ_RK') seq";
			$seq=($db->query($sql));
			$seq='RK'.$seq[0]['seq'];

			//条形码sql语句
			$codeSQL="SELECT nextval('SEQ_CODE') code";

			$storageDB=M('storage');
			$numberDB=M('number');
			for ($i=0; $i <$count ; $i++) {
				$code=($db->query($codeSQL));
				$code='TXM'.$code[0]['code'];
				$data=array(
					'code'=>$code,
					'goods_id'=>$arr['goods_id'][$i],
					'depot_id'=>$depot_id,
					'supplier_id'=>$supplier_id,
					'price'=>$arr['goods_price'][$i],
					'createtime'=>$t,
					'edittime'=>$t,
					'uid'=>session('uid')
				);
				if($db->add($data)){

				}else{
					$this->error('商品编码插入失败，请重试！');
				}
				$data2=array(
					'sequence'=>$seq,
					'number'=>$arr['goods_number'][$i],
					'date'=>$date,
					'createtime'=>$t,
					'edittime'=>$t,
					'sender'=>$arr['sender'],
					'receive'=>$arr['receive'],
					'code_code'=>$code,
					'uid'=>session('uid')
				);
				if($storageDB->add($data2)){
				}else{
					$this->error('入库记录插入失败，请重试！');
				}
				$data3=array(
					'code_code'=>$code,
					'income'=>$arr['goods_number'][$i]
				);
				if($numberDB->add($data3)){
				}else{
					$this->error('商品库存插入失败，请重试！');
				}
			}
			$this->success('添加成功');
		}else{
			$this->display();
		}

	}

	//入库日志
	public function record(){
		$pageNum=I('pageNum',1,intval);//第几页
		$numPerPage=I('numPerPage',10,intval);//每页显示条数
		//获取排序的字段及排序方式
		$orderField=$_POST['_order']?$_POST['_order']:'id';
		$orderDirection=$_POST['_sort']?$_POST['_sort']:'asc';
		//组合排序字符串
		$orders=($orderField.' '.$orderDirection);
		//加载检索的基础数据
		$this->search();
		//检索条件
        if($_POST['search_where']){
            $this->search_where=$_POST['search_where'];
        }
        $where=$this->_search();

    	//在where条件中增加未删除的判断条件
       	$where['del']=array('eq','0');

		$db=D('StorageView');
		//获取总数据条数
		$count=$db->where($where)->group('sequence')->count();
		$this->assign('totalCount',$count);//数据的总条数
		$this->assign('numPerPage',$numPerPage);//每页显示多少条
		$this->assign('pageNumShown',6);//页标数字多少个
		$this->assign('currentPage',$pageNum);//当前是第几页
		$page= new \Think\Page($count,$numPerPage);
		$field=array('sequence','date','sender','receive','status','uid','depot_name','supplier_name','sum(number) as sum','sum(number*price) as jine');
 		$this->list=$db->limit($numPerPage)->Page($pageNum)->order($orders)->field($field)->where($where)->group('sequence')->select();
 		$this->display();
	}

	//批量删除入库记录，并将商品出入库数据删除
	public function allDelete(){
		if(!empty($_POST)){
			$ids=$_POST['ids'];
			if(isset($ids)){
				$codes=M(CONTROLLER_NAME)->where(array('id'=>array('in',$ids)))->getField('code_code',true);
				if (M(CONTROLLER_NAME)->where(array('id'=>array('in',$ids)))->setField('del',1)) {
					if(M('code')->where(array('code'=>array('in',$codes)))->setField('del',1)){
						if (M('number')->where(array('code_code'=>array('in',$codes)))->delete()) {
							$this->success ('删除成功');
						}else {
	                    	$this->error ('入库数量删除失败');
	            		}
	                } else {
	                    $this->error ('商品编码删除失败');
	                }
	            }else{
	            	$this->error ('入库纪录删除失败');
	            }
			}
		}
	}
	//将记录由正常状态改为删除状态,并将商品出入库数据删除
	public function delete(){
		$id = $_GET['id'];
		if(isset($id)){
			$code=M(CONTROLLER_NAME)->where(array('id'=>$id))->getField('code_code');
			if (M(CONTROLLER_NAME)->where(array('id'=>$id))->setField('del',1)) {
				if(M('code')->where(array('code'=>$code))->setField('del',1)){
					if (M('number')->where(array('code_code'=>$code))->delete()) {
						$this->success ('删除成功');
					}else {
                    	$this->error ('入库数量删除失败');
            		}
                } else {
                    $this->error ('商品编码删除失败');
                }
            }else{
            	$this->error ('入库纪录删除失败');
            }
		}
	}
	//修改商品入库数量及价格，并更新出入库数据
		public function edit(){
		if(!empty($_POST)){
			$db=M(CONTROLLER_NAME);
			if($_POST['oldnumber']==$_POST['number']||$db->save($_POST)){
				if($_POST['oldprice']==$_POST['price']||M('code')->where(array('code'=>$_POST['code']))->setField('price',$_POST['price'])){
 					if($_POST['oldnumber']==$_POST['number']||M('number')->where(array('code_code'=>$_POST['code']))->setField('income',$_POST['number'])){
						$this->success('更新成功');
					}else{
						$this->error ('入库数量更新失败！');
					}
				}else{
					$this->error ('商品价格更新失败！');
				}
			}else{
				$this->error('入库明细更新失败');
			}
		}else{
			$id=$_GET['id'];
			$db=D(StorageView);
			$this->list=$db->field('id,number,price,code')->find($id);
			$this->display();
		}
	}
	public function out(){
		$where=session('excel_where');
		$field=array("FROM_UNIXTIME(date,'%Y年%m月%d日') as date",'sequence','code','goods_name','xinghao','guige','unit','number','price','supplier_name','depot_name','sender','receive',"if(storage.status=1,'初始创建','已经审核') as status");
		$db=D('StorageView');
		$data=$db->where($where)->field($field)->order($orders)->select();
		$row=array('sequence','date','code','supplier_name','depot_name','goods_name','xinghao','guige','unit','price','number','sender','receive','status');
		$data=array_sort($data,$row);		
    	//导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
		import("Org.Util.PHPExcel");
		import("Org.Util.PHPExcel.Writer.Excel5");
		import("Org.Util.PHPExcel.IOFactory.php");
		$filename="入库明细";
		$headArr=array('出库编码','出库日期','物料编码','供应商名称','仓库名称','物料名称','型号','规格','单位','价格','数量','送货人','收货人','状态');
		$this->getExcel($filename,$headArr,$data);
	}
}